<template>
  <view class="page">
    <view class="top flex">
      <view :class="type == 1 ? 'top-item active' : 'top-item'" @click="handletype(1)">我参加的({{ form_1.total }})</view>
      <view :class="type == 2 ? 'top-item active' : 'top-item'" @click="handletype(2)">我发布的({{ form_2.total }})</view>
    </view>
    <view class="top-1 flex">
      <view :class="active == 1 ? 'top-1-1 active' : 'top-1-1'" @click="handleActive(1)">进行中</view>
      <view :class="active == 2 ? 'top-1-1 active' : 'top-1-1'" @click="handleActive(2)">已完成</view>
    </view>
    <view class="kong" style="height: 202rpx;"></view>
    <block v-if="type == 1">
      <view class="box" v-for="(item, index) in list" :key="item.id">
        <view class="box-title flex">
          <view class="ox-title-2">{{ item.active_status }}</view>
          <view class="box-title-2" v-if="item.is_used_datetime">验票时间：{{ item.is_used_datetime }}</view>
          <view class="box-title-2 flex" v-else @click="handleNav('./my/activeCode?id=' + item.activity_id)">
            <image :src="imgApi+'images/wallet/icon-29.svg'" mode="scaleToFill" />活动码
          </view>
        </view>
        <view class="box-con flex">
          <image :src="showImgApi+item.activity.poster_img" mode="scaleToFill" />
          <view class="box-con-right">
            <view class="box-con-right-1">活动主题：{{ item.activity.theme }}</view>
            <view class="box-con-right-2">时间：{{ item.start_date }}</view>
            <view class="box-con-right-2">地址：{{ item.province ? '线上' : "线下" }}活动</view>
            <view class="box-con-right-2" v-if="item.item.province">地址：{{ item.province }}{{ item.city }}{{ item.county
              }}{{
                item.address }}</view>
            <view class="box-con-right-2">主办方：{{ item.activity.activity_sponsor.name }}</view>
          </view>
        </view>
        <view class="box-bottom flex" style="justify-content: flex-end;">
          <view class="box-b-1 flex" @click="handleRefund(item.id)" style="margin-right: 29rpx;" v-if="!item.is_used_datetime">
            <image :src="imgApi+'images/wallet/icon-30.svg'" mode="scaleToFill" />
            退款申请
          </view>
          <view class="box-b-1 flex" @click="handleShop(item.id)" v-if="!item.is_used_datetime">
            <image :src="imgApi+'images/wallet/icon-29.svg'" mode="scaleToFill" />
            验票码
          </view>
        </view>
      </view>
    </block>
    <block v-else>
      <view class="box" v-for="(item, index) in list" :key="item.id">
        <view class="box-title flex">
          <view class="box-title-2">{{ item.active_status }}</view>
        </view>
        <view class="box-con flex">
          <image :src="showImgApi+item.poster_img" mode="scaleToFill" />
          <view class="box-con-right">
            <view class="box-con-right-1">活动主题</view>
            <view class="box-con-right-2">时间：{{ item.start_date }}</view>
            <view class="box-con-right-2">{{ obj[item.activity_format] }}活动</view>
            <view class="box-con-right-2" v-if="item.item.province">地址：{{ item.province }}{{ item.city }}{{ item.county
              }}{{
                item.address }}</view>
            <view class="box-con-right-2">主办方：蚂蚁团建</view>
          </view>
        </view>
        <view class="box-bottom flex">
          <view class="box-b-1 flex" @click="handleNav('./my/activeCode?id=' + item.id)">
            <image :src="imgApi+'images/wallet/icon-29.svg'" mode="scaleToFill" />
            活动码
          </view>
          <view class="box-b-1 flex" @click="handleNav('./my/poster?id=' + item.id)">
            <image :src="imgApi+'images/wallet/icon-28.svg'" mode="scaleToFill" />
            生成海报
          </view>
          <view class="box-b-1 flex">
            <image :src="imgApi+'images/wallet/icon-27.svg'" mode="scaleToFill" />
            验票记录
          </view>
          <view class="box-b-1 flex" @click="handleScance">
            <image :src="imgApi+'images/wallet/icon-26.svg'" mode="scaleToFill" />
            验票
          </view>
          <view class="box-b-1 flex">
            <image :src="imgApi+'images/wallet/icon-23.svg'" mode="scaleToFill" />
            导出
          </view>
        </view>
      </view>
    </block>
    <u-empty mode="data" v-if="list.length==0">
    </u-empty>
    <u-popup :show="show" @close="show = false" mode="center" :round="10">
      <view class="er">
        <tki-qrcode v-if="ifShow" cid="qrcode1" ref="qrcode" :val="val" :size="size" :unit="unit" :background="background" :foreground="foreground" :pdground="pdground" :icon="icon" :iconSize="iconsize" :lv="lv"
          :onval="onval" :loadMake="loadMake" :usingComponents="true" @result="qrR" />
        <view class="text">请将此二维码给工作人员进行核销二维码仅限使用一次</view>
      </view>
    </u-popup>
    <view class="kong"></view>
    <view class="bottom-flex" @click="handleNav('/pagesB/active/activeOne')">
      <view class="btn">发起活动</view>
    </view>
  </view>
</template>
<script>
import {
  activityOrderList,
  getActivityList,
  refund,
  checkTicket,
} from "@/utils/request.js";
import tkiQrcode from "./components/tki-qrcode/tki-qrcode.vue";
export default {
  data() {
    return {
      imgApi: this.$config.imgApi,
      showImgApi: this.$config.showImgApi,
      idEntity: "",
      ifShow: true,
      val: "", // 要生成的二维码值
      size: 150, // 二维码大小
      unit: "rpx", // 单位
      background: "#ffffff", // 背景色
      foreground: "#000000", // 前景色
      pdground: "#000000", // 角标色
      icon: "", // 二维码图标
      iconsize: 20, // 二维码图标大小
      lv: 3, // 二维码容错级别 ， 一般不用设置，默认就行
      onval: true, // val值变化时自动重新生成二维码
      loadMake: true, // 组件加载完成后自动生成二维码
      src: "", // 二维码生成后的图片地址或base64
      shareIshow: false,
      type: 1,
      active: 1,
      list: [],
      show: false,
      form_1: {
        p: 0,
        n: 10,
        in_progress: true,
        total: 0,
      },
      form_2: {
        p: 0,
        n: 10,
        get_my_list: true,
        in_progress: true,
        total: 0,
      },
      total_1: 0,
      obj: {},
      type: 1,
      isScanning: false,
    };
  },
  onLoad() {
    if (!uni.getStorageSync("userInfo")) {
      uni.showModal({
        title: "提示",
        content: "请先登陆再进行操作",
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            uni.navigateTo({
              url: "/pagesB/login/login",
            });
          }
        },
      });
    } else {
      this.getActivityOrderList();
    }
  },
  components: {
    tkiQrcode,
  },
  onReachBottom() {
    if (this.type == 1) {
      if (this.list.length < this.total_1) {
        this.form_1.p++;
        this.getActivityOrderList();
      }
    } else {
      if (this.list.length < this.total_1) {
        this.form_2.p++;
        this.getList();
      }
    }
  },
  methods: {
    async refund(data) {
      return await refund(data);
    },
    async checkTicket(data) {
      return await checkTicket(data);
    },
    handleNav(url) {
      console.log("url", url);
      uni.navigateTo({
        url: url,
      });
    },
    handleScance() {
      let that = this;
      if (that.isScanning) return;
      uni.scanCode({
        success: function (res) {
          const data = { order_id: res.result.split("=")[1] };
          that.checkTicket(data).then((res) => {
            if (res) {
              uni.showToast({
                title: "验票成功",
                icon: "none",
              });
            }
          });
        },
        fail: function (err) {
          console.error("扫码失败：", err);
        },
        complete: function () {
          setTimeout(() => {
            that.isScanning = false;
          }, 500); // 延迟500毫秒后允许再次调用
        },
      });
    },
    qrR(img) {
      this.img = img;
    },
    handleRefund(id) {
      const data = { order_id: id };
      this.refund(data).then((res) => {
        if (res) {
          uni.showToast({
            title: "操作成功",
            icon: "none",
            mask: true,
          });
          setTimeout(() => {
            this.form_1.p = 0;
            this.list = [];
            this.getActivityOrderList();
          }, 1500);
        }
      });
    },
    parseDate(dateString) {
      const [datePart, timePart] = dateString.split(" ");
      const [year, month, day] = datePart.split("-");
      const [hours, minutes, seconds] = timePart.split(":");
      return new Date(year, month - 1, day, hours, minutes, seconds);
    },
    getActivityStatus(item, currentDateTime) {
      const startDate = this.parseDate(item.start_date);
      const endDate = this.parseDate(item.end_date);
      const currentDate = this.parseDate(currentDateTime);
      if (currentDate < startDate) {
        return "活动未开始";
      } else if (currentDate >= startDate && currentDate <= endDate) {
        return "活动进行中";
      } else {
        return "活动已结束";
      }
    },
    // 解码，输出：中文
    decodeStr(str) {
      var out, i, len, c;
      var char2, char3;
      out = "";
      len = str.length;
      i = 0;
      while (i < len) {
        c = str.charCodeAt(i++);
        switch (c >> 4) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            // 0xxxxxxx
            out += str.charAt(i - 1);
            break;
          case 12:
          case 13:
            // 110x xxxx 10xx xxxx
            char2 = str.charCodeAt(i++);
            out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
            break;
          case 14:
            // 1110 xxxx 10xx xxxx 10xx xxxx
            char2 = str.charCodeAt(i++);
            char3 = str.charCodeAt(i++);
            out += String.fromCharCode(
              ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
            );
            break;
        }
      }
      return out;
    },
    scanCodeH5() {
      uni.chooseImage({
        count: 1,
        success: (imgRes) => {
          Qrcode.qrcode.decode(this.getObjectURL(imgRes.tempFiles[0]));
          Qrcode.qrcode.callback = (codeRes) => {
            if (codeRes.indexOf("error") >= 0) {
              // 二维码识别失败
              this.qrCodeRes = "不合法二维码：" + codeRes;
            } else {
              // 二维码识别成功
              let r = this.decodeStr(codeRes);
            }
          };
        },
      });
    },
    async getActivityList(data) {
      return await getActivityList(data);
    },
    async activityOrderList(data) {
      return await activityOrderList(data);
    },
    handleShop(item) {
      this.show = true;
      this.val = `order_id=${item}`;
    },
    getActivityOrderList() {
      this.activityOrderList(this.form_1).then((res) => {
        this.form_1.total = res.count;
        this.list = [...res.list, ...this.list];
        this.total_1 = res.count;
      });
    },
    getList() {
      this.getActivityList(this.form_2).then((res) => {
        if (res.count < 1) {
          this.$data.uEmptyText = "暂无数据";
          return false;
        }
        let nowDate = res.date;
        if (res.list.length > 0) {
          let list = [...this.list, ...res.list];
          list.forEach((item) => {
            item.active_status = this.getActivityStatus(item, nowDate);
          });
          this.form_2.total = res.count;
          this.obj = res.activity_format;
          this.total_1 = res.count;
          this.list = list;
        } else {
          this.list = [];
        }
      });
    },
    handletype(type) {
      this.type = type;
      this.list = [];
      this.active = 1;
      if (this.type == 1) {
        this.form_1.p = 0;
        this.getActivityOrderList();
      } else {
        this.form_2.p = 0;
        this.getList();
      }
    },
    handleActive(active) {
      this.active = active;
      this.list = [];
      if (this.type == 1) {
        this.form_1.p = 0;
        if (this.active == 1) {
          this.form_1.in_progress = true;
          delete this.form_1.complete;
        } else {
          delete this.form_1.in_progress;
          this.form_1.complete = true;
        }
        this.getActivityOrderList();
      } else {
        this.form_2.p = 0;
        if (this.active == 1) {
          this.form_2.in_progress = true;
          this.form_2.complete = false;
        } else {
          this.form_2.in_progress = false;
          this.form_2.complete = true;
        }
        this.getList();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.kong {
  height: 200rpx;
}
.bottom-flex {
  width: 100%;
  height: 105rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-bottom: 30rpx;
}
.er {
  width: 568rpx;
  height: 568rpx;
  left: 0;
  right: 0;
  margin: 0 auto;
  overflow: hidden;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  .text {
    text-align: center;
    width: 435rpx;
    margin: 40rpx auto 0;
  }
}

.box {
  width: 640rpx;
  padding: 0 27rpx;
  background: #ffffff;
  border-radius: 15rpx;
  margin: 20rpx auto 0;

  .box-bottom {
    padding: 20rpx 0;
    border-top: 1rpx solid#D7D7D7;
    justify-content: space-between;

    .box-b-1 {
      justify-content: center;
      font-size: 23rpx;
      color: #ffb850;

      image {
        width: 30rpx;
        height: 30rpx;
        margin-right: 10rpx;
      }
    }
  }

  .box-title {
    justify-content: space-between;
    font-size: 23rpx;
    padding: 22rpx 0;
    border-bottom: 1rpx solid#D7D7D7;

    .box-title-2 {
      color: #ffb850;

      image {
        width: 30rpx;
        height: 30rpx;
        margin-right: 10rpx;
      }
    }
  }

  .box-con {
    padding: 23rpx 0;

    image {
      width: 150rpx;
      height: 197rpx;
      border-radius: 10rpx;
    }

    .box-con-right {
      flex: 1;
      margin-left: 30rpx;
      font-size: 23rpx;

      .box-con-right-1 {
        color: #000000;
      }

      .box-con-right-2 {
        color: #7f7f7f;
        margin-top: 25rpx;
      }
    }
  }
}

.top {
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  height: 93rpx;
  background: #ffffff;
  z-index: 9;

  .top-item {
    flex: 1;
    text-align: center;
    font-size: 25rpx;
    height: 100%;
    line-height: 93rpx;
  }

  .active {
    color: #ffbb50;
    position: relative;

    &::after {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translate(-50%, 0);
      background: #ffb850;
      width: 100rpx;
      height: 5rpx;
      content: "";
    }
  }
}

.top-1 {
  width: 100%;
  position: fixed;
  height: 115rpx;
  background: #f2f2f2;
  top: 85rpx;
  left: 0;

  .top-1-1 {
    padding: 8rpx 16rpx;
    background: #ffffff;
    border-radius: 40rpx;
    text-align: center;
    font-size: 26rpx;
    margin-left: 25rpx;
  }

  .active {
    background: #ffbb50;
    color: #ffffff;
  }
}
</style>